package com.you.open.api.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.you.api.common.util.ApiModelProperty;
import com.you.open.api.demo.entity.RequestVo;
import com.you.open.api.demo.entity.ResponseFieldVo;
import com.you.open.api.demo.entity.ResponseVo;
import com.you.open.api.demo.service.IOpenApiService;
import com.you.open.api.demo.service.biz.IUserBizService;
import com.you.simple.demo.api.entity.UserInfo;
import com.yough.api.framework.bean.ApiDocumentBean;
import com.yough.api.framework.bean.DocumentBeanDefinition;
import com.yough.api.framework.constant.DocumentConstants;
import com.yough.api.framework.core.message.IMessageHandler;
import com.yough.api.framework.core.message.process.XmlMessageHandler;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description
 * @Author yough
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/1/14
 */
@Service
public class OpenApiServiceImpl implements IOpenApiService {

    @Autowired
    private IUserBizService userBizService;

    @Override
    public ResponseVo apiService(Map requestMap) throws Exception {
        // 获取apiId
        String apiId = (String) requestMap.get("apiId");
        // 根据apiId获取请求参数信息
        ConcurrentHashMap<String, ApiDocumentBean> apiDocumentBeanMap = DocumentConstants.apiDocumentBeanMap;
        ApiDocumentBean apiDocumentBean = apiDocumentBeanMap.get(apiId);
        Class<?> methodParamClassType = apiDocumentBean.getMethodParamClassType();
        // 将请求参数Map转换为请求参数的实体类
        Object object = JSON.parseObject(JSON.toJSONString(requestMap), methodParamClassType);
        System.out.println(object);
        // 得到返回参数类型
        Class<?> methodResultClassType = apiDocumentBean.getMethodResultClassType();
        // 模拟请求后端，得到数据
        String repsonseXml = userBizService.requestBiz(null);
        // 解析返回的xml报文
        IMessageHandler messageHandler = new XmlMessageHandler();
        // 生成实例对象
        List<ResponseFieldVo> responseFieldVos = new ArrayList<>();
        ResponseFieldVo responseFieldVo = null;
        try {
            Element responseNode = messageHandler.getResponseNode(repsonseXml);
            // 解析响应参数节点
            Iterator<Element> responseResultIter = responseNode.elementIterator();
            // Object resultObj = methodResultClassType.getConstructor().newInstance();
            while (responseResultIter.hasNext()) {
                Element responseResultNode = (Element) responseResultIter.next();
                System.out.println("response result: " + responseResultNode.getName() + "->" + responseResultNode.getText());
                // 进行字段匹配
                Field declaredField = methodResultClassType.getDeclaredField(responseResultNode.getName());
                if (declaredField != null) {
                    responseFieldVo = new ResponseFieldVo();
                    responseFieldVo.setResultType(declaredField.getType().getSimpleName());
                    responseFieldVo.setResultName(responseResultNode.getName());
                    ApiModelProperty memberAnnotation = declaredField.getAnnotation(ApiModelProperty.class);
                    if (memberAnnotation != null) {
                        responseFieldVo.setResultDesc(memberAnnotation.value());
                    }
                    responseFieldVo.setResultValue(responseResultNode.getText());
                    responseFieldVos.add(responseFieldVo);
                    // 设置属性的值
                    // declaredField.setAccessible(true);
                    // this.setValue(declaredField, responseResultNode.getText(), resultObj);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // 返回结果
        System.out.println(responseFieldVos);
        ResponseVo responseVo = new ResponseVo();
        responseVo.setResponseFieldVos(responseFieldVos);
        return responseVo;
    }

    /**
     * 设置字段的值
     *
     * @param declaredField
     * @param textValue
     * @param instObj
     * @throws Exception
     */
    private void setValue(Field declaredField, String textValue, Object instObj) throws Exception {
        String fieldType = declaredField.getType().getSimpleName();
        if (("int").equals(fieldType) || ("Integer").equals(fieldType)) {
            // int类型的处理
            int value = Integer.valueOf(textValue);
            declaredField.set(instObj, value);
            return;
        } else if (("Date").equals(fieldType)) {
            // 日期类型的处理
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYYMMddHHmmss");
            Date value = simpleDateFormat.parse(textValue);
            declaredField.set(instObj, value);
            return;
        }
        declaredField.set(instObj, textValue);
    }
}
